#include <iostream>
#include <string>
#include <unordered_map>
#include "log.hpp"
static const std::string Dafaultpath = "./dictionary.txt";
using namespace LogModule;
class Dict
{
private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _key_val;

public:
    Dict()
    {
    }
    bool LoadDict(const std::string &path = Dafaultpath)
    {
        _dict_path = path;
        std::ifstream ifs(_dict_path);
        if (!ifs.is_open())
        {
            LOG(Loglevel::ERROR) << "无法打开词典文件: " << _dict_path;
            return false;
        }
        std::string line;
        while (std::getline(ifs, line))//getline,获得不了一行时会返回零
        {
            if (line.empty())
                continue;
            std::istringstream iss(line);
            std::string key;
            if (!(iss >> key))
                continue; // 没有 key，跳过

            // 读取剩余部分作为 value
            std::string val;
            std::getline(iss, val);

            // 去掉开头多余的空格
            if (!val.empty() && val[0] == ' ')
                val.erase(0, val.find_first_not_of(' '));
            _key_val[key] = val;
        }

        LOG(Loglevel::INFO) << "词典加载完成，共 " << _key_val.size() << " 条";
        return true;
    }
    std::string translate(const std::string &key)
    {
        auto it = _key_val.find(key);
        if (it != _key_val.end())
        {
            LOG(Loglevel::DEBUG) << "翻译成功: " << key << " -> " << it->second;
            return it->second;
        }
        else
        {
            LOG(Loglevel::DEBUG) << "未找到翻译: " << key;
            return key; // 原样返回，或者可以返回 "[UNKNOWN]"
        }
    }
    ~Dict()
    {
    }
};